<template>
    <div class="">
        <el-dialog :title="addForm.id > 0 ? '修改居民' : '添加居民'" :close-on-click-modal="false" style="width: 650px; display: flex;flex-direction: column; align-items: center;"
            v-model="dialogVisible" :before-close="handleClose">
            {{ addForm }}
            <el-form :rules="rules" ref="ruleFormRef" :model="addForm" class="elform" style="width: 350px;" label-width="auto">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="addForm.title" />
                </el-form-item>

                <el-form-item label="位置" prop="name">
                    <el-select clearable v-model="addForm.typeid" style="width:120px" placeholder="请选择状态">
                        <el-option v-for="item in typelist" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="URL" prop="title">
                    <el-input v-model="addForm.url" />
                </el-form-item>

                <el-form-item label="图片" class="picture">
                    <el-upload class="avatar-uploader" :headers="headers" :action="uploadUrl" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.picture" :src="baseUrl + addForm.picture" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="标题" prop="title">
                    <el-input-number v-model="addForm.sort" :min="1" :max="10" controls-position="right" size="large" />
                </el-form-item>

                <el-form-item label="是否显示">
                    <el-radio-group v-model="addForm.enabled">
                        <el-radio :value="1" size="large">是</el-radio>
                        <el-radio :value="0" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUserInfo">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script lang='ts' setup>
import { ref, reactive, onMounted } from "vue"
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { addtype } from '../service/advertisement/type'
import {adtypelist,advertisementadd,advertisementget } from '../service/advertisement/advertisement'

import { useStore } from "../store/index"
import { storeToRefs } from "pinia"

const store = useStore()

const { token } = storeToRefs(store)
const headers = { Authorization: token.value }
const uploadUrl = import.meta.env.VITE_BASE_URL + "upload/add";
const baseUrl = import.meta.env.VITE_IMG_URL

const porps = defineProps(["id"])

type type = {
    id: number;
    name: string;
}

const typelist = ref<type[]>([])
const gettype = async ()=>{
    let res = await adtypelist()
    typelist.value = res.data.list
}


//提交
const addUserInfo = async () => {
    let res: any = await advertisementadd(addForm).catch(() => { })
    console.log(res);
    if (res.errCode == 10000) {
        ElMessage.success(res.errMsg)
        emit('update', true)
        dialogVisible.value = false
    } else {
        ElMessage.error(res.errMsg)
    }

}

//图片上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
) => {
    console.log(response);
    if (response.errCode === 10000) {
        addForm.picture = response.data;
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片需要是jpg或png格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片不能超过2MB!')
        return false
    }
    return true
}

const emit = defineEmits(['close', 'update'])
const dialogVisible = ref(true)

let addForm = reactive<addtype>({
    id: 0,
    title: "",
    picture: "",
    sort: 0,
    typeid: null,
    url: "",
    enabled: 0
})
const handleClose = () => {
    dialogVisible.value = false
    emit('close', [])
}



const validatePass2 = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入姓名'))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    name: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
    name: [{ validator: validatePass2, trigger: 'blur' }],
})

let buildid: number[] = []

const getone = async () => {
    let res = await advertisementget(porps.id)
    console.log(res,22);
    Object.assign(addForm,res.data)
}

onMounted(() => {
    gettype()
    if (porps.id) {
        getone()
    }
})
</script>

<style lang="less" scoped>
.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}
/deep/ .avatar-uploader .el-upload {
  width: 80px;
  height: 80px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
</style>
